﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebAPITest.Models;
using WebAPITest.Models.Database;

namespace WebAPITest.Service
{
    public class UserService: IUserService
    {
        private readonly WebEnterpriseIIContext _db;
        /// <summary>
        /// 服务的构造函数
        /// </summary>
        /// <param name="db"></param>
        public UserService(WebEnterpriseIIContext db)
        {
            _db = db;
        }

        /// <summary>
        /// 根据用户名获取用户
        /// </summary>
        /// <returns></returns>
        public User GetUserByUserName(string userName)
        {
            //第一步 从数据库查询用户为username的用户 
            var user = _db.Users.FirstOrDefault(x => x.UserName == userName);
            return user;
        }
        //服务层方法做的事   接口
        //1、传入数据        1、前端传入数据
        //2、处理数据        2、接口处理数据
        //3、返回结果        3、返回结果给前端
        public bool ExistUserByUserName(string userName)
        {
            return _db.Users.Any(x => x.UserName == userName);
        }
        /// <summary>
        /// 添加一个新用户
        /// </summary>
        public int AddNewUser(string username,string email,string nickname,string password)
        {
            var user = new User()
            {
                UserName = username,
                Email = email,
                NickName = nickname,
                Password = password,
                CreateTime = DateTime.Now,
                Salt = 0,
                UserLevel = 1,
            };
            //上下文.表名.操作方法(需要插入的数据对象)
            _db.Users.Add(user);
            //保存更改 影响行数
            var row = _db.SaveChanges();
            if(row>0)
                return user.UserId;
            return 0;
        }
    }
}
